package com.guli.common.utils;
/*
 * @Author 罗
 * @date 2020/10/19 - 12:19 下午
 */

import com.guli.common.constant.ProtocolEnum;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class HttpUtils {


    /**
     * POST---有参测试(普通参数)
     * 一旦 response.close(); 之后 就获取不到 response.getEntity();了，就算获取到，里面也没有想要的信息
     */
    public static CloseableHttpResponse post(String url) throws IOException {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        // 响应模型
        CloseableHttpResponse response = null;

        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            // responseEntity = response.getEntity();

            //System.out.println("响应状态为:" + response.getStatusLine());
        /*if (responseEntity != null) {
            System.out.println("响应内容长度为:" + responseEntity.getContentLength());

            System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); （响应实体只能格式化一次）
        }*/

        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return response;
    }

    /**
     * @param protocol http/ https
     * @param host     api.weibo.com
     * @param path     /2/users/show.json
     * @param params   List<NameValuePair> params = new ArrayList<>();
     *                 params.add(new BasicNameValuePair("access_token", "2.00t6iYAE8ckusD748828bae8ku5NWC"));
     *                 params.add(new BasicNameValuePair("uid", "3672805221"));
     * @return
     */
    public static HttpResponse get(ProtocolEnum protocol, String host, String path, List<NameValuePair> params) throws IOException, URISyntaxException {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 设置uri信息,并将参数集合放入uri;
        // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
        URI uri = new URIBuilder()
                .setScheme(protocol.getProtocol())
                .setHost(host)
                .setPort(protocol.getPort())
                .setPath(path)
                .setParameters(params)  // 将参数放入键值对类NameValuePair中,再放入集合中
                .build();

        // 创建Get请求
        HttpGet httpGet = new HttpGet(uri);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            /*HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }*/
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }
}
